package org.apli.haiam.servlet;

import com.apli.controladores.AplinfoFactoryBean;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.List;
import java.util.ResourceBundle;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apli.haiam.ejb.entidades.AdmMenu;
import org.apli.haiam.ejb.entidades.AdmSistema;
import org.apli.haiam.ejb.interfaces.AdministradorLoginHaiam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Permite cerrar una sesion en el sistema.
 * <p>
 * 
 * <H6>Soporte:HAIAM
 * <I>david_s_1086@hotmail.com,david.carranza@haiam.gob.ec</I></H6>
 *
 * @author david Carranza
 * @version 1.0 30/07/2014
 */
@WebServlet(name = "LoginOut", urlPatterns = {"/LoginOut"})
public class LoginOut extends HttpServlet {

    private AdministradorLoginHaiam adminLogin;
    private static String _SIS;
    final Logger log = LoggerFactory.getLogger(LoginOut.class);

    /**
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
     * methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
            _SIS = request.getContextPath();

            cargarEjb();
            AdmSistema sistemaPrincipal = (AdmSistema) request.getServletContext().getAttribute("sistemaPrincipal");
            AdmSistema sistema = (AdmSistema) request.getServletContext().getAttribute("sistema");
            String sisHost = (sistemaPrincipal.getHost() == null || sistemaPrincipal.getHost().length() < 3) ? "" : sistemaPrincipal.getHost();
            String sisContextPath = (sistemaPrincipal.getContextPath() == null || sistemaPrincipal.getContextPath().length() < 3) ? request.getContextPath() : sistemaPrincipal.getContextPath();
            Date fecha = new Date();
//            try {
//                fecha = adminLogin.getFechaDb();
//            } catch (Exception e) {
//            }
            if (sisContextPath.equals(request.getContextPath())) {
                log.info(_SIS + " **** LoginOut() Cerrando sesión en equipo LOCAL({}) y redirecionando a {}", request.getContextPath(), sisContextPath);
                HttpSession session = request.getSession(false);
                try {
                    session.invalidate();
                } catch (Exception e) {
                }
                // carga los datos del sistema principal
                log.info(_SIS + " ----------------------------");
                List<AdmMenu> menu = null;
                try {
                    menu = adminLogin.getMenuBase(sistemaPrincipal);
                    log.info(_SIS + " LoginOut(..) SISTEMA GLOBAL UTILIZADO {}", sistemaPrincipal);
                } catch (Exception e) {
                    try {
                        menu = adminLogin.getMenuBase(sistema);
                    } catch (Exception ex) {
                    }
                    log.info(_SIS + " LoginOut(..) No existe sistema global ...");
                }
                request.getSession().removeAttribute("menu");
                request.getSession().setAttribute("menu", menu);
                request.getServletContext().removeAttribute("menu");
                request.getServletContext().setAttribute("menu", menu);
                request.getServletContext().removeAttribute("fecha");
                request.getServletContext().setAttribute("fecha", fecha);
                log.info(_SIS + " ----------------------------");
                //--
                try {
                    response.sendRedirect(sisContextPath + "/index.jsp");
                } catch (IOException e) {
                    log.error(_SIS + " LoginOut() {} ", e.getMessage());
                }
            } else {
                log.info(_SIS + " **** LoginOut() Cerrando sesión en equipo LOCAL({}) y redirecionando para cerrar sesion en {}", request.getContextPath(), sisContextPath);
                HttpSession session = request.getSession(false);
                try {
                    session.invalidate();
                } catch (Exception e) {
                }
                // carga los datos del sistema principal
                log.info(_SIS + " ----------------------------");
                List<AdmMenu> menu = null;
                try {
                    menu = adminLogin.getMenuBase(sistemaPrincipal);
                    log.info(_SIS + " LoginOut(..) SISTEMA GLOBAL UTILIZADO {}", sistemaPrincipal);
                } catch (Exception e) {
                    try {
                        menu = adminLogin.getMenuBase(sistema);
                    } catch (Exception ex) {
                    }
                    log.info(_SIS + " LoginOut(..) No existe sistema global ...");
                }
                request.getSession().removeAttribute("menu");
                request.getSession().setAttribute("menu", menu);
                request.getServletContext().removeAttribute("fecha");
                request.getServletContext().setAttribute("fecha", fecha);
                log.info(_SIS + " ----------------------------");
                //--
                try {
                    response.sendRedirect((sisHost == null ? "" : sisHost) + sisContextPath + "/LoginOut");
                } catch (IOException e) {
                    log.error(_SIS + " LoginOut() {} ", e.getMessage());
                }
            }
        } finally {
            out.close();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

    /**
     * Obtiene el objeto remoto.
     */
    protected void cargarEjb() {
        if (adminLogin == null) {
            String ejbPath = null;
            try {
                ResourceBundle property = getProperties();
                String ORBContext = property.getString("ORBContext");
                String ejbContextPath = property.getString("ejb.context.path.admin");
                ejbPath = ORBContext + ejbContextPath + "/AdministradorLoginBean";
                adminLogin = (AdministradorLoginHaiam) AplinfoFactoryBean.lookupBean(ejbPath, false);
//                try {
//                    adminLogin.getFechaDb();
//                } catch (Exception e) {
//                }
            } catch (Exception e) {
                log.error(_SIS + " cargarEjb() {} - {} ", ejbPath, e.getMessage());
            }
        }

    }

    protected ResourceBundle getProperties() {
        return ResourceBundle.getBundle("aplicacion");
    }
}
